/**
 * Created by   :宁建浩
 * Created time :2017/4/11/12:38
 * File explain :施小包资金账户-账单
 */

require.config({
  baseUrl: "../../libs",
  paths: {
    jquery: ["jquery/jquery-1.11.3"],
	vue: ["./vue2-4-1/vue"],
	header:["../components/my-header"],
    menu:["../components/my-menu"],
    layer: ["layer/layer"],
    zui: ["zui/js/zui"],
    boot: ["bootstrap-3.3.7-dist/js/bootstrap"],
    bootTable: ["bootstrap-table-dist/dist/js/bootstrap-table"],
    bootTableCN: ["bootstrap-table-dist/dist/locale/bootstrap-table-zh-CN"],
    config: ["../common/js/common-config"],
    page: ["../common/js/qhpager"],
    datetimepicker: ["datetimepicker/js/datetimepicker"]
  }
});
require(["jquery"], function () {
  require(["bootTable"], function () {
    require(["vue","header","menu","layer", "zui", "boot", "bootTableCN", "config", "page", "datetimepicker"], operationCodeFun)
  });
});
//代码容器

function operationCodeFun(vue,header,menu) {
  "use strict";
  const QHConfig = $("body").data("config");//配置文件常量
  const userCode = window.sessionStorage.getItem("userCode");//班组信息
  var manageDetail = JSON.parse(window.sessionStorage.getItem("detail"));//获得角色信息
  var tableLoadFlag = false;//防连续表格刷新
  var ajaxFlag = null;//定时器防连续点击
  var traderType = {};//交易类型
  var traderStatus = {};//交易状态
  var userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));//获取用户信息，判断用户是什么以什么角色登录的
  var userRole = userInfo[0].roleId || userInfo[0].companyType;//用户角色标识符
  //alert(JSON.stringify(userInfo));
  //layer框架配置
  layer.config({
    path: "../../libs/layer/"
  });
  window.initTop(vue);
  window.initMenu(vue);
  getTrader();//获得交易类型
  QHConfig.chooseDate();
  getRoleData();
  function getRoleData() {
    $.ajax(tokenAjax({
      type: "GET",
      async: false,
      url: QHConfig.url.payCenterDetail,
      success: function (res) {
        var manageInfo = res.data;
        window.sessionStorage.setItem("detail", JSON.stringify(manageInfo));
      }
    }));
  }

  $("[data-name='startTime']").on("change", function () {
    $("[data-name='endTime']").datetimepicker("setStartDate", $(this).val());
  });
  // 发货日期结束时间
  $("[data-name='endTime']").on("change", function () {
    $("[data-name='startTime']").datetimepicker("setEndDate", $(this).val());
  });
  //面包屑
  $(".cmn-crumb").on("click", "a.cmn-bread-0", breadClick);
  //筛选
  $(".account-detail").on("click", "span", searchClick);
  $(".cmn-query-blue-calendar").on("change", changeTimeFun);
  //交易关闭弹出框 //去付款事件
  $("#id-receipt-list").on("click", ".pay-close", clickCloseFun).on("click", ".pay-wait", clickPayFun);//
  //商品列表表格属
  var tableOption = {
    undefinedText: "-",
    ajax: tableAjax,
    url: QHConfig.url.getBillPageByAccountId,
    onPreBody: function () {//移除默认分页器
      $(".fixed-table-pagination").remove();
    },
    onLoadSuccess: tableSucFun,//表格加载成功后回调
    queryParams: queryParams,//表格刷新回调
    responseHandler: function (res) {
      return resHandler(res);
    }
  };
  var nowDate = QHConfig.timeFmt(new Date(), 3);
  var nowMon = new Date().getMonth() + 1;
  var nowYea = new Date().getFullYear();
  var nowDay = new Date().getDate();
  $("[data-name='startTime']").val(nowYea + "-" + ((nowMon - 1) > 10 ? (nowMon - 1) : "0" + (nowMon - 1)) + "-" + (nowDay>10?nowDay:"0"+nowDay));
  $("[data-name='endTime']").val(nowDate);
  $("#id-receipt-list").bootstrapTable(tableOption);//表格提交数据
  /*
   * 该函数用于表格自定义分页器:
   * @author 宁建浩
   * @Date   2017/3/19
   **/
  var options = {
    tag_Class: 'cmn-page_tag',//分页标签默认样式
    tag_on_Class: 'cmn-page_tag_on',//分页标签选中样式
    input_Class: 'cmn-pageInput',//分页搜索框样式
    showTags: 5,//标签省略距离
    pageSearch: true,//是否启用页面搜索跳转
    pageSizes: [10, 20, 50],
    pageSizeDefault: 10
  };
  window.QHPagination.init($(".cmn-table-pager"), outHandler, options);//分页
  //提交表格搜索条件
  function queryParams(params) {
    var msg = getQueryData();
    params.pageNum = (params.offset / params.limit) + 1;
    params.pageSize = $("[data-name='_p_size']").val();
    $.extend(params, msg);
    return params;
  }

  //获得交易类型
  function getTrader() {
    $.ajax(tokenAjax({
      type: 'GET',
      async: false,
      url: QHConfig.url.tradeType+userRole,
      success: function (res) {
        traderType = res.data;//支付类型
        var html = ' <span class="txt-distance active" data-tradeType="">全部</span>';
        $.each(traderType, function (k, v) {
          html += ` <span class="txt-distance" data-tradeType="${k}">${v}</span>`;
        });
        $(".bill-inline-block1").html(html);
      }
    }));
    $.ajax(tokenAjax({
      type: 'GET',
      async: false,
      url: QHConfig.url.tradeStatus,
      success: function (res) {
        traderStatus = res.data;//支付类型
        var html = ' <span class="txt-distance active" data-status="">全部</span>';
        $.each(traderStatus, function (k, v) {
          html += ` <span class="txt-distance" data-status="${k}">${v}</span>`;
        });
        $(".bill-inline-block2").html(html);
      }
    }));
  }

  //获取搜索信息
  function getQueryData() {
    var msg = {};//搜索需要的所有数据Date.parse(new Date());
    var fatherEle = $(".account-detail");//父元素
    var statTime = fatherEle.find(".form-date[data-name='startTime']").val();//开始时间
    var endTime = fatherEle.find(".form-date[data-name='endTime']").val();//结束时间
    msg.tradeType = fatherEle.find("span.active[data-tradeType]").attr("data-tradeType");//订单类型
    msg.status = fatherEle.find("span.active[data-status]").attr("data-status");//订单状态
    msg.beforeMonth = fatherEle.find("span.active[data-beforeMonth]").attr("data-beforeMonth");//月份
    //判断是否有时间
    if (!statTime || !endTime) {
      msg.startTime = "";
      msg.endTime = "";
    } else {
      msg.startTime = Date.parse(new Date(statTime));
      msg.endTime = Date.parse(new Date(endTime)) + 57600000;
    }
    //判断是否是今天
    if (msg.beforeMonth == "today") {
      msg.beforeMonth = "";
      msg.startTime = new Date(new Date().toLocaleDateString()).getTime();
      msg.endTime = new Date(new Date().toLocaleDateString()).getTime() + 86400000;
    } else if (msg.beforeMonth == "all") {
      msg.beforeMonth = "";
      msg.startTime = "";
      msg.endTime = "";
    }
    return msg;
  }

  //用于获得表格数据后处理
  function resHandler(res) {
    var needData = {};//表格数据
    //如果成功响应，否则空数组
    if (res.status == 200) {
      $.each(res.data.list, function (k, v) {
        cycleTableData(k, v);
      });
      //需要的数据
      needData.rows = res.data.list;
      needData.total = res.data.total;
      window.QHPagination.setParameters(res.data.pageNum, res.data.pageSize, res.data.pages);
      window.QHPagination.render(res.data.pageNum);
    } else {
      needData.rows = [];
      needData.total = 0;
    }
    return needData;
  }

  //表格加载成功回调
  function tableSucFun(data) {
    tableLoadFlag = true;
  }

  //循环表格数据，处理需要的处理的数据
  function cycleTableData(k, v) {
    var msg = JSON.stringify(v);
    v.createdAtTH = QHConfig.timeFmt(v.createdAt, 6);
    if(v.tradeType=="提现" || v.tradeType=="充值"){
      v.statusTH = "";
    }else{
      if((v.status == "处理中"||v.status=="等待付款") && v.fundFlow == '资金流出'){
        if (userRole == 5 && (v.tradeType.indexOf("分包款")!=-1)) {
          v.statusTH = "";
        }else{
          v.statusTH = `<span class="cmn-device-leave pay-close" data-bill='${JSON.stringify(v)}'>交易关闭</span>
                      <span class="wait-pay-txt pay-wait" data-bill='${JSON.stringify(v)}'>付款</span>`;
        }
      }
    }

    if (v.fundFlow == "资金流出"&&v.tradeType!="提现"&&v.tradeType!="充值") {
      v.amountTH = "-" + thousandsBits(v.amount);
    } else if(v.fundFlow == "资金流入"&&v.tradeType!="提现"&&v.tradeType!="充值"){
      v.amountTH = "+" + thousandsBits(v.amount);
    }else{
      v.amountTH = thousandsBits(v.amount);
    }

  }

  //数字千分位
  function thousandsBits(num) {
    if (!num) {
      return "0.00";
    } else {
      num = num.toString().replace(/\$|\,/g, '');
      num = Number(num).toFixed(2);
      if (num > -1000 && num < 1000) {
        return num;
      }
      var sign = num.indexOf("-") > 0 ? '-' : '';
      var cents = num.indexOf(".") > 0 ? num.substr(num.indexOf(".")) : '';
      cents = cents.length > 1 ? cents : '';
      num = num.indexOf(".") > 0 ? num.substring(0, (num.indexOf("."))) : num;
      if ('' == cents) {
        if (num.length > 1 && '0' == num.substr(0, 1)) {
          return 'Not a Number ! ';
        }
      }
      else {
        if (num.length > 1 && '0' == num.substr(0, 1)) {
          return 'Not a Number ! ';
        }
      }
      for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
      }
      return sign + num + cents;
    }
  }

  //执行bootstrap分页跳转
  function outHandler() {
    $("#id-receipt-list").bootstrapTable("selectPage", window.QHPagination.getPage());
  }

  //筛选样式
  function searchClick() {
    var dateNear = $(this).data("beforemonth");
    $(this).addClass("active").siblings("span").removeClass("active");
    if (dateNear) {
      var nowDate = QHConfig.timeFmt(new Date(), 3);
      var nowMon = new Date().getMonth() + 1;
      var nowYea = new Date().getFullYear();
      var nowDay = new Date().getDate();
      $("[data-name='startTime'],[data-name='endTime']").val("");
      if (dateNear == 1) {
        $("[data-name='startTime']").val(nowYea + "-" + ((nowMon - 1) > 10 ? (nowMon - 1) : "0" + (nowMon - 1)) + "-" + (nowDay>10?nowDay:"0"+nowDay));
        $("[data-name='endTime']").val(nowDate);
      } else if (dateNear == 3) {
        $("[data-name='startTime']").val(nowYea + "-" + ((nowMon - 3) > 10 ? (nowMon - 3) : "0" + (nowMon - 3)) + "-" + (nowDay>10?nowDay:"0"+nowDay));
        $("[data-name='endTime']").val(nowDate);
      } else if (dateNear == 12) {
        $("[data-name='startTime']").val(nowYea - 1 + "-" + (nowMon > 10 ? nowMon : "0" + nowMon) + "-" + (nowDay>10?nowDay:"0"+nowDay));
        $("[data-name='endTime']").val(nowDate);
      } else if (dateNear == "today") {
        $("[data-name='startTime']").val(nowDate);
        $("[data-name='endTime']").val(nowDate);
      } else if (dateNear == "all") {
        $("[data-name='startTime']").val("");
        $("[data-name='endTime']").val("");
      }
    }
    if (tableLoadFlag) {
      ajaxFlag = null;
      ajaxFlag = setTimeout(function () {
        tableRefresh();
      }, 300);
      tableLoadFlag = false;
    }
  }

  //时间筛选功能
  function changeTimeFun() {
    var startTime = $("[data-name='startTime']").val();
    var endTime = $("[data-name='endTime']").val();
    if (startTime && endTime) {
      tableRefresh();
      $(".change-before-time").find(".active").removeClass("active");
      var nowTime = Date.parse(new Date());//现在的一个月前
      var startTimeNum = Date.parse(startTime);
      var oneMon = nowTime - 86400000 * 30;//开始时间的一个月前
      var threeMon = nowTime - 86400000 * 90;//开始时间的一个月前
      var yearMon = nowTime - 86400000 * 365;//一年前毫秒
      if (startTimeNum > yearMon) {
        $("[data-beforemonth='12']").addClass("active").siblings(".active").removeClass("active");
        if (startTimeNum > threeMon) {
          $("[data-beforemonth='3']").addClass("active").siblings(".active").removeClass("active");
          if (startTimeNum > oneMon) {
            $("[data-beforemonth='1']").addClass("active").siblings(".active").removeClass("active");
          }
        }
      }
    }
  }

  //表格刷新
  function tableRefresh() {
    $("#id-receipt-list").bootstrapTable("refresh");
  }

  //交易关闭弹出框
  function clickCloseFun() {
    var that = this;
    var billId = $(that).data("bill");//当前账单数据
    layer.confirm("您确定要关闭交易吗？关闭后，不能恢复", {
      btn: ["确定关闭", "取消"],
      title: "温馨提示"
    }, function () {
      $.ajax(tokenAjax({
        type: "PUT",
        url: QHConfig.url.billClose + "?accountBillId=" + billId.id,
        contentType: "application/json;charset=UTF-8",
        success: function (res) {
          if (res.message == "success") {
            tableRefresh();
          } else {
            layer.msg(res.message);
          }
        },
        error: function () {
          layer.alert("网络错误");
        }
      }));
      layer.closeAll();
    });
  }

  //去付款回调
  function clickPayFun() {
    var that = this;
    getBIzzSn(that);
  }

  //获取账单的bizzSn和bizzSys，关闭交易和去交易时需要
  function getBIzzSn(that) {
    var billId = $(that).data("bill");//当前账单数据
    var txt = "";//当前账单类型
    var typeTradeSn=0;
    $.each(traderType, function (k, v) {
      if (v == billId.tradeType) {
        txt = k;
      }
    });

    $.ajax(tokenAjax({
      type:"POST",
      url:QHConfig.url.accountBillId+billId.id,
      contentType: "application/json;charset=UTF-8",
      dataType:"json",
      success:function(res){
        var payUrl = "";
        var msg = res.data;
        if(res.status==400){
          layer.msg(res.message)
        }else{
          if(billId.tradeType == "充值"){
            payUrl = "pages/project-recharge/project-recharge.html" + "?transfer=" + txt + "&balance=" + manageDetail.availableBalance+ "&amount=" + billId.amount + "&bizzSn=" + msg.bizzSn + "&operName=" + billId.mainAccountRealName + "&userCode=" + userCode;
          }else{
            payUrl = "pages/buyer-pay/buyer-pay.html" + "?transfer=" + txt + "&balance=" + manageDetail.availableBalance
              + "&amount=" + billId.amount + "&bizzSn=" + msg.bizzSn + "&operName=" + billId.mainAccountRealName + "&accountName=" + billId.oppositeAccountUserCode + "&userCode=" + userCode + "&bizzSys=" + msg.bizzSys+"&tradeMemo="+billId.tradeMemo+"&formBill=true";
          }
          layerNew(payUrl);
        }
      }
    }));
  }

  //跳转到支付页面
  function layerNew(url) {
    parent.layer.open({
      title: false,
      shade: 0.8,
      move: false,
      closeBtn: 0,
      resize: false,
      scrollbar: false,
      type: 2,
      area: ['100%', '100%'],
      content: url
    })
  }

  function breadClick() {
    parent.$("#id-main-frame").attr("src", "pages/my-account/my-account.html").click();
  }
}